#include "Communication.h"
//#include "JniHelper.h"

JavaVM* CppToJavaCommunication::vm = nullptr;

CppToJavaCommunication::CppToJavaCommunication() {}

CppToJavaCommunication::~CppToJavaCommunication() {}

JavaVM* CppToJavaCommunication::getJavaVM() {
    return vm;
}

void CppToJavaCommunication::setJavaVM(JavaVM *javaVM) {
    vm = javaVM;
}

const char* CppToJavaCommunication::GetExternalPath()
{
    JNIEnv *env = nullptr;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4) != JNI_OK) {
        return nullptr;
    }
    jboolean isCopy;
    jclass cls =  (*env).FindClass("com/gary/cmakejniapplication/Utils");
    jmethodID activityMethod = env->GetStaticMethodID(cls, "getDiskFilesDir", "()Ljava/lang/String;");
    jstring _InternalFileDir = (jstring)(env)->CallStaticObjectMethod(cls, activityMethod, NULL);
    const char* InternalFileDir = env->GetStringUTFChars(_InternalFileDir,&isCopy);

    env->DeleteLocalRef(cls);
    return InternalFileDir;
}

void CppToJavaCommunication::SetSavePath(char *path)
{
    JNIEnv *env = nullptr;
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4) != JNI_OK) {
        return;
    }

    // 获取Java类
    jclass cls = (*env).FindClass("com/gary/cmakejniapplication/Utils");
    if(cls == NULL)
    {
        return ;
    }

    // 实例化要调用的Java方法
    jmethodID savePathID = (*env).GetMethodID( cls, "SetSavePath", "(Ljava/lang/String;)V");	// 获取JNIDemo类的构造方法
    if(savePathID == NULL)
    {
        printf("GetMethodID for constructor!\n");
        return;
    }
    // 创建对应的Java对象
    // <init>对应的是调用构造函数
    jmethodID InitMethodID = env->GetMethodID(cls,"<init>","()V");
    jobject new_object = env->NewObject(cls, InitMethodID);

    jstring pjstring = env->NewStringUTF(path);
    env->CallVoidMethod(new_object,savePathID,pjstring);
    env->DeleteLocalRef(cls);
    return;
}

int CppToJavaCommunication::GetIntNumber()
{
    return -1;
}

void CppToJavaCommunication::SetIntNumber(int value) {}